﻿namespace BM.Tools.WebControls.MForm.ScriptReferences
{
    using System;
    using System.Text;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.Design;
    using System.Web.UI.HtmlControls;

    using AjaxControlToolkit;

    /// <summary>
    /// A static class that makes including embedded resources easier
    /// </summary>
    public static class ScriptIncluder
    {
        /// <summary>
        /// includes associated scripts
        /// </summary>
        /// <param name="control">
        /// The control.
        /// </param>
        public static void IncludeResources(Control control)
        {
            IncludeResources(control.Page, control.GetType());            
        }

        /// <summary>
        /// includes associated scripts
        /// </summary>
        /// <param name="page">
        /// The current page.
        /// </param>
        /// <param name="type">
        /// The type that keeps resource meta information.
        /// </param>
        public static void IncludeResources(Page page, Type type)
        {
            var scriptManager = ScriptManager.GetCurrent(page);
            if (scriptManager == null)
            {
                return;
            }

            foreach (ScriptReference sr in ScriptObjectBuilder.GetScriptReferences(type))
            {
                scriptManager.Scripts.Add(sr);
            }
        }

        internal static HtmlHead CreateOrGetHeader(Page page)
        {           
            if (page.Header != null)
            {
                return page.Header;
            }

            var header = new HtmlHead();
            page.Controls.AddAt(0, header);
            return header;
        }

        internal static string MapPath(bool designMode, Page page, string endPath)
        {
            var builder = new StringBuilder(GetPath(designMode, page));
            if (!builder.ToString().EndsWith("/", StringComparison.Ordinal))
            {
                builder.Append("/");
            }

            builder.Append(endPath);
            return builder.ToString();
        }

        private static string GetPath(bool designMode, Page page)
        {
            if (designMode)
            {                
                return GetDesignModePath(page);
            }

            return HttpContext.Current.Request.ApplicationPath;
        }

        private static string GetDesignModePath(Page page)
        {
            var webApplication = (IWebApplication)page.Site.GetService(typeof(IWebApplication));
            return webApplication.RootProjectItem.PhysicalPath;
        }        
    }
}